package com.open.pingban.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.duowan.mobile.netroid.Listener;
import com.duowan.mobile.netroid.NetroidError;
import com.duowan.mobile.netroid.RequestQueue;
import com.duowan.mobile.netroid.request.FileDownloadRequest;
import com.duowan.mobile.netroid.toolbox.FileDownloader;
import com.open.pingban.R;
import com.open.pingban.netroid.Netroid;
import com.open.pingban.utils.OPENLOG;
import com.open.pingban.utils.OpenFileUtils;

import java.io.File;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * 打开文档的东西，先需要下载存储在缓存路径，然后打开.
 */
public class OpenFileActivity extends BaseActivity {

    File mSaveDir;
    @InjectView(R.id.progressBar3)
    ProgressBar progressBar3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_open_file);
        ButterKnife.inject(this);
        progressBar3.setMax(100);
        Intent intent = getIntent();

        initNetroid(); // 初始化 netroid.

        mSaveDir = new File(Environment.getExternalStorageDirectory(), getPackageName());
        if (!mSaveDir.exists()) mSaveDir.mkdir();

        if (intent != null) {
            String fileName = intent.getStringExtra("fileName");
            String url = intent.getStringExtra("downUrl");
            final File storeFile = new File(mSaveDir, fileName);
//            url = "http://download.game.yy.com/duowanapp/m/Duowan20140427.apk";
            url = OpenFileUtils.getOsDisplay(url);
            OPENLOG.D("path:" + storeFile.getPath() + " url:" + url);
            if (!storeFile.exists()) {
                FileDownloader fileDownloader = Netroid.getFileDownloader();
                fileDownloader.add(storeFile.getPath(), url, new Listener<Void>() {
                    @Override
                    public void onSuccess(Void response) {
                        openFileActivity(storeFile);
                    }

                    @Override
                    public void onProgressChange(long fileSize, long downloadedSize) {
                        float value = (downloadedSize * 1.0f / fileSize * 100);
                        progressBar3.setProgress((int) value);
                    }

                    @Override
                    public void onError(NetroidError error) {
                        OPENLOG.E("error:" + error.getMessage());
                    }
                });
            } else { // 如果本地已经存在，直接打开.
                try {
                    openFileActivity(storeFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void openFileActivity(File storeFile) {
        OPENLOG.D("正准备打开文档... ...");
        Intent intent = OpenFileUtils.openFile(storeFile);
        if (intent != null) {
//            finish(); // 防止整个桌面退出，重写加载了.
            startActivity(intent);
        } else {
            Toast.makeText(getApplicationContext(), "打开文件失败", Toast.LENGTH_SHORT).show();
        }
    }

    protected void initNetroid() {
        Netroid.init(null);
        RequestQueue requestQueue = Netroid.getRequestQueue();
        Netroid.setFileDownloder(new FileDownloader(requestQueue, 1) {
            @Override
            public FileDownloadRequest buildRequest(String storeFilePath, String url) {
                FileDownloadRequest fileDownloadRequest = new FileDownloadRequest(storeFilePath, url) {
                    @Override
                    public void prepare() {
                        addHeader("Accept-Encoding", "identity");
                        super.prepare();
                    }
                };
                return fileDownloadRequest;
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        Netroid.getFileDownloader().clearAll();
//        Netroid.destroy();
    }
}
